package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //1. 判断是否为登录操作,如果是,直接放行
        String path = request.getURI().getPath();  // api/v1/channel/list  /login/in
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }

        //2. 获取请求头中的token,如果没有直接返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //3. 校验token是否有效,如果无效,直接返回401
        Claims claims = AppJwtUtil.getClaimsBody(token);
        if (claims == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4. 如果有效从token中解析出userId和name放到请求头中继续进入到后面的微服务中
        int type = AppJwtUtil.verifyToken(claims);
        //-1：有效，0：有效
        if (type == -1 || type == 0) {
            Integer userId = claims.get("userId", Integer.class);
            String name = claims.get("name", String.class);
            request.mutate().header("userId", userId.toString());
            request.mutate().header("name", name);
            return chain.filter(exchange);  //放行
        }else{
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}